package com.hp.team.bookstore.dbutil.init;

import com.hp.team.bookstore.dbutil.dao.DAOFactory;
import com.hp.team.bookstore.dbutil.dao.HibernateUtil;
import com.hp.team.bookstore.dbutil.dao.catalog.ProductHibernateDAO;
import com.hp.team.bookstore.dbutil.dao.order.PurchaseOrderHibernateDAO;
import com.hp.team.bookstore.dbutil.dao.order.PurchaseOrderItemHibernateDAO;
import com.hp.team.bookstore.model.catalog.Product;
import com.hp.team.bookstore.model.order.PurchaseOrder;
import com.hp.team.bookstore.model.order.PurchaseOrderItem;

public class PurchaseOrderItemInitializer {

	private static ProductHibernateDAO productDAO;
	private static PurchaseOrderItemHibernateDAO orderItemDAO;
	private static PurchaseOrderHibernateDAO orderDAO;

	static {
		DAOFactory daoFactory = new DAOFactory();
		productDAO = daoFactory.getProductDAO();
		orderItemDAO = daoFactory.getPurchaseOrderItemDAO();
		orderDAO = daoFactory.getPurchaseOrderDAO();
	}

	public static void init() {

		orderItemDAO.setSession(HibernateUtil.getSessionFactory().getCurrentSession());
		HibernateUtil.beginWriteTransaction();

		for (int i = 0; i < 10; i++) {
			PurchaseOrder order = orderDAO.findById((long) (i + 4) / 3, false);
			PurchaseOrderItem orderItem = createOrderItem(i);

			orderItem.setOrder(order);
			orderItemDAO.makePersistent(orderItem);

			order.addOrderItem(orderItem);
			orderDAO.makePersistent(order);
		}

		HibernateUtil.commitTransaction();
	}

	public static PurchaseOrderItem createOrderItem(long id) {
		PurchaseOrderItem orderItem = new PurchaseOrderItem();

		for (int i = 0; i < 10; i++) {
			Product book = productDAO.findById(id + 1, true);
			orderItem.setBook(book);
			orderItem.setQuantity((int) id + i);
		}

		return orderItem;
	}

}
